//
//  ViewController.swift
//  1.12.Presenting Sharing Options with UIActivityViewController
//
//  Created by joker on 15/7/21.
//  Copyright (c) 2015年 joker. All rights reserved.
//

import UIKit

class ViewController: UIViewController, UITextFieldDelegate {

    var textField: UITextField!
    var buttonShare: UIButton!
    
    func createTextField(){
        textField = UITextField(frame: CGRect(x: 20, y: 35, width: 280, height: 30))
        textField.borderStyle = .RoundedRect
        textField.placeholder = "Enter text to share ..."
        textField.delegate = self
        view.addSubview(textField)
    }
    
    func createButton(){
        buttonShare = UIButton.buttonWithType(.System) as? UIButton
        buttonShare.frame = CGRect(x: 20, y: 80, width: 280, height: 44)
        buttonShare.setTitle("Share", forState: .Normal)
        
        buttonShare.addTarget(self, action: "handleShare:", forControlEvents: .TouchUpInside)
        view.addSubview(buttonShare)
    }
    func handleShare(sender: UIButton) {
        
        if textField.text.isEmpty {
            let message = "Please enter a text and then press Share"
            
            let alertController = UIAlertController(title: nil, message: message, preferredStyle: .Alert)
            
            alertController.addAction(UIAlertAction(title: "OK", style: .Default, handler: nil))
            
            presentViewController(alertController, animated: true, completion: nil)
            return
        }
        
        let activityViewController = UIActivityViewController(activityItems: [textField.text as NSString], applicationActivities: nil)
        
        presentViewController(activityViewController, animated: true, completion: nil)
    }
    override func viewDidLoad() {
        super.viewDidLoad()
        // Do any additional setup after loading the view, typically from a nib.
        createButton()
        createTextField()
    }

    override func didReceiveMemoryWarning() {
        super.didReceiveMemoryWarning()
        // Dispose of any resources that can be recreated.
    }

    func textFieldShouldReturn(textField: UITextField) -> Bool {
        textField.resignFirstResponder()
        return true
    }
}

